package aa

import (
	"encoding/json"
	"fmt"
	"ginDemo/common/typ"
	"ginDemo/common/version"
	"io/ioutil"
	"os"
	"path/filepath"
	"time"

	"gitee.com/clearluo/gotools/util"
	"gitee.com/clearluo/gotools/zaplog"
	_ "gitee.com/clearluo/gotools/zaplog"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

var (
	configObj *typ.ConfigT
	logObj    *zap.Logger
	jsonPath  = filepath.Join(util.GetBinDir(), "config")
)

func init() {
	configObj = &typ.ConfigT{}
	initIni()
	initLog()
	initData()
}
func initData() {

}
func initIni() {
	viper.AddConfigPath(filepath.Join(util.GetBinDirNew(), "config"))
	viper.SetConfigName("config")
	viper.SetConfigType("json")
	var err error
	if err = viper.ReadInConfig(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		panic(err)
	}
	if err = viper.Unmarshal(configObj); err != nil {
		fmt.Fprintln(os.Stderr, err)
		panic(err)
	}

}
func initLog() {
	logDir := configObj.Log.Dir
	if logDir == "" {
		logDir = "logs"
	}
	logPath := filepath.Join(util.GetBinDirNew(), logDir)
	logObj = zaplog.Init(&zaplog.LogConfig{
		LogDir:         logPath,
		WithMaxAge:     time.Hour * 24 * 7,
		IsPrintConsole: version.IsDevelopment(),
		FileSplitTime:  time.Hour * 24,
	})
	zaplog.Infof("config.json:%v", util.AssertMarshal(configObj))
	zaplog.Infof("appInfo:%v", version.PrintVersion())
}

func GetLogDir() string {
	return configObj.Log.Dir
}
func GetOutHttpPort() int {
	return configObj.OutHttp.Port
}
func GetLogObj() *zap.Logger {
	return logObj
}

// 启动加载
func readData(jsonName string, value interface{}) error {
	b, err := ioutil.ReadFile(filepath.Join(jsonPath, jsonName+".json"))
	if err != nil {
		zaplog.Warnf("read %v err:%v", jsonName, err)
		return err
	}
	if err := json.Unmarshal(b, value); err != nil {
		zaplog.Warnf("read %v err:%v", jsonName, err)
		return err
	}
	return nil
}
